export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		//设置cart
		updateCart(state, cart) {
			state.cart = cart
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//全选/反选
		updateAllChecked(state, checked) {
			state.cart.forEach(e => e.goods_state = checked)
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//删除商品
		updateRemoveGoods(state, goods) {
			state.cart = state.cart.filter(e => e.goods_id !== goods.goods_id)
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//修改商品数量
		updateGoodsCount(state, goods) {
			//console.log(state, goods)
			//找到商品
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if (!!findRes) {
				//修改goods_count
				findRes.goods_count = goods.goods_count
			}
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//在数组中找到要修改的对象
		updateGoodsState(state, goods) {
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if (!!findRes) {
				//把他的goods_state取反
				findRes.goods_state = !findRes.goods_state
			}
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//加入购物车
		updateAddCart(state, goods) {
			//找是否存在这件商品
			const findRes = state.cart.find(e => e.goods_id === goods.goods_id)
			if (!!findRes) {
				//如果存在就让数量加1
				findRes.goods_count++
			} else {
				//如果不存在push
				state.cart.push(goods)
			}
			//持久化存储
			this.commit('m_cart/saveToStorage')
		},
		//持久化存储
		saveToStorage(state) {
			//持久化
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		//已勾选商品总金额
		checkedPrice(state) {
			let sum = 0
			state.cart.forEach(e => {
				if (e.goods_state) {
					sum += (e.goods_price * e.goods_count)
				}
			})
			return sum.toFixed(2)
		},
		//已勾选商品数量
		checkedCount(state) {
			let sum = 0
			state.cart.forEach(e => {
				if (e.goods_state) {
					sum += e.goods_count
				}
			})
			return sum
		},
		//全部商品数量
		allGoodsCount(state) {
			let sum = 0
			state.cart.forEach(e => {
				sum += e.goods_count
			})
			return sum
		}
	}
}
